﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using FastReport;
using FastReport.Export.Pdf;
using LongSCADA_WPF.Helpers;
using LongSCADA_WPF.Models;
using LongSCADA_WPF.Services;
using MiniExcelLibs;
using MySqlConnector;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace LongSCADA_WPF.ViewModels
{
    public partial class DataQueryViewModel:ObservableObject
    {
        private readonly UserModelService _userModelService;
        public DataQueryViewModel(UserModelService userModelService)
        {
            _userModelService = userModelService;
        }

        #region 条件处理
        [ObservableProperty]
        List<ScadaReadData> _dataQueryList = new();

        [ObservableProperty]
        DateTime _startTime = DateTime.Now.AddDays(-2);

        [ObservableProperty]
        DateTime _endTime = DateTime.Now;

        [RelayCommand]
        void Load()
        {
            Search();
        }
        [RelayCommand]
        void Search()
        {
            int totalNumber = 1;
            if (StartTime > EndTime)
            {
                _userModelService.ShowMessage("开始时间不能大于结束时间");
                return;
            }
            DataQueryList = SqlSugarHelper.Db.Queryable<ScadaReadData>()
               .Where(x => x.UpdateTime >= StartTime && x.UpdateTime <= EndTime)
               .ToPageList(CurrentPage,PageSize,ref totalNumber);

            TotalPages =(int) Math.Ceiling((double)totalNumber / PageSize);
        }
        [RelayCommand]
        void Reset()
        {
            StartTime = DateTime.Now.AddDays(-2);
            EndTime = DateTime.Now;
            DataQueryList = SqlSugarHelper.Db.Queryable<ScadaReadData>().ToList();
        }
        #endregion

        #region 分页实现
        [ObservableProperty]
        int _pageSize = 20;

        [ObservableProperty]
        int _currentPage = 1;
        partial void OnCurrentPageChanged(int value)
        {
            //当属性值改变时，执行方法
            Search();
        }
        [ObservableProperty]
        int _totalPages = 1;

        [RelayCommand]
        void GotoFirstPage()
        {
            CurrentPage = 1;
        }
        [RelayCommand]
        void GotoLastPage()
        {
            CurrentPage = TotalPages;
        }
        [RelayCommand]
        void GotoNextPage()
        {
            if (CurrentPage >= TotalPages)
            {
                _userModelService.ShowMessage("操作不合法");
                return;
            }
            CurrentPage++;
        }
        [RelayCommand]
        void GotoPreviousPage()
        {
            if (CurrentPage <= 1)
            {
                _userModelService.ShowMessage("操作不合法");
                return;
            }
            CurrentPage--;
        }
        #endregion

        #region 导出数据
        [RelayCommand]
        void OutPage()
        {
            SavebyMiniExcel(DataQueryList);
        }
        [RelayCommand]
        void OutAll()
        {
            SavebyMiniExcel(SqlSugarHelper.Db.Queryable<ScadaReadData>().ToList());
        }

        private void SavebyMiniExcel<T>(List<T> dataList)
        {
            if (dataList == null || dataList.Count == 0)
            {
                return;
            }
            string savePath = AppDomain.CurrentDomain.BaseDirectory + "\\Excels\\";
            
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
            try
            {
                MiniExcel.SaveAs(savePath + fileName, dataList);
                _userModelService.ShowMessage($"{fileName}--导出成功");
            }
            catch (Exception ex)
            {

               _userModelService.ShowMessage("导出失败：" + ex.Message);
            }

        }
        #endregion

        #region 报表数据
        [RelayCommand]
        void DesignReport()
        {
            try
            {
                //FastReport 
                Report report = new Report();
                report.Load(Environment.CurrentDirectory + "\\Configs\\report.frx");
                report.Design();

                //导出PDF
               /* PDFExport pDFExport = new PDFExport();
                pDFExport.Export(report);*/
                report.Dispose();
                _userModelService.ShowMessage("报表设计成功");
                
            }
            catch (Exception e)
            {

               _userModelService.ShowMessage(e.Message);
            }
        }
        [RelayCommand]
        void PreviewReport()
        {
            try
            {
                System.Data.DataSet dataSet = _dataQueryList.ConvertToDataSet();
                //FastReport 
                Report report = new Report();
                report.Load(Environment.CurrentDirectory + "\\Configs\\report.frx");
                report.RegisterData(dataSet);
                report.Prepare();
                report.ShowPrepared();
                report.Dispose();
            }
            catch (Exception e)
            { 
              _userModelService.ShowMessage(e.Message);
            }
        }
        [RelayCommand]
        void OutputReport()
        {

        }
        #endregion
    }
}
